package com.tacademy.android.lbs.location;

import java.util.List;

import org.restlet.data.CharacterSet;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.representation.Variant;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

import com.tacademy.android.lbs.location.model.Place;

public class LocationRestlet extends ServerResource {
	private LocationService locationService = new LocationService();
	
	public LocationService getLocationService() {
		return locationService;
	}

	public void setLocationService(LocationService locationService) {
		this.locationService = locationService;
	}

	@Get
	public Representation toXml(Variant variant) {
		Representation result = null;
		String locationId = (String)getRequest().getAttributes().get("location_id");
		
    	if (locationId != null) {
    		Place place = locationService.getPlace(locationId);
    		
    		StringBuilder xmlStrBuilder = new StringBuilder();
			xmlStrBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			if (place != null) {
				xmlStrBuilder.append(place.xmlString());
			}
			
			result = new StringRepresentation(xmlStrBuilder, MediaType.TEXT_XML, Language.ALL, CharacterSet.UTF_8);
    	} else { //all
    		List<Place> places = locationService.getAllPlaces();
    		
    		StringBuilder xmlStrBuilder = new StringBuilder();
			xmlStrBuilder.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			xmlStrBuilder.append("<places>\n");
			for (Place place : places) {
				xmlStrBuilder.append(place.xmlString());
			}
			xmlStrBuilder.append("</places>\n");
			
			result = new StringRepresentation(xmlStrBuilder, MediaType.TEXT_XML, Language.ALL, CharacterSet.UTF_8);
    	}
        return result;
	}
}
